package de.tsystems.dict.api.impl;

import de.tsystems.dict.model.Identifiable;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import javax.inject.Inject;
import java.io.Serializable;
import java.util.List;

public abstract class AbstractDao<T extends Identifiable> implements Dao<T> {
    @Inject
    SessionFactory sessionFactory;

    @Override
    public T getById(Serializable id) {
        return (T) getCurrentSession().get(getEntityClass(), id);
    }

    @Override
    public List<T> listAll() {
        return getCurrentSession()
                .createQuery("from " + getEntityClass().getName()).list();
    }

    @Override
    public T save(T entity) {
        if (entity.getId() == null) {
            getCurrentSession().persist(entity);
            return entity;
        } else {
            return (T) getCurrentSession().merge(entity);
        }
    }

    @Override
    public void update(T entity) {
        getCurrentSession().merge(entity);
    }

    @Override
    public void remove(T t) {
        getCurrentSession().delete(t);
    }

    @Override
    public void delete(T entity) {
        getCurrentSession().delete(entity);
    }

    protected final Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }
}
